from django.contrib import admin
from django.utils.html import format_html
from django.db.models import Count, Q, Avg
from django.utils.safestring import mark_safe
from django.http import JsonResponse
from django.urls import path, reverse
from django.shortcuts import redirect
from django.conf import settings
from datetime import datetime, timedelta
from .models import Battle, BattleRound, BattleStatistics, MatchQueue
from .dashboard import DashboardView, user_detail_dashboard
import json


class BattleRoundInline(admin.TabularInline):
    model = BattleRound
    extra = 0
    readonly_fields = ('timestamp',)
    fields = ('round_number', 'player1_actions', 'player2_actions', 'timestamp')
    max_num = 10  # 限制显示的回合数
    can_delete = False

    def get_queryset(self, request):
        """优化回合查询性能"""
        queryset = super().get_queryset(request)
        return queryset.select_related('battle').order_by('round_number')

    class Media:
        css = {
            'all': ('admin/css/battle_rounds.css',)
        }
        js = ('admin/js/battle_rounds.js',)

@admin.register(Battle)
class BattleAdmin(admin.ModelAdmin):
    list_display = ('id', 'player1', 'player2', 'get_player1_win_rate', 'get_player2_win_rate', 'status', 'result', 'get_exciting_display', 'excitement_score', 'created_at', 'total_rounds', 'get_duration', 'get_winner_display')
    list_filter = ('status', 'result', 'is_exciting', 'is_manually_marked', 'created_at', 'player1_code__language', 'player2_code__language')
    search_fields = ('player1__username', 'player2__username', 'player1_code__title', 'player2_code__title')
    readonly_fields = ('created_at', 'started_at', 'finished_at', 'total_rounds', 'excitement_calculated_at', 'get_battle_analysis', 'get_performance_chart')
    inlines = [BattleRoundInline]
    actions = ['export_battle_data', 'analyze_selected_battles', 'mark_as_exciting', 'unmark_as_exciting', 'calculate_excitement_scores']

    def changelist_view(self, request, extra_context=None):
        """自定义changelist视图，添加额外的上下文"""
        extra_context = extra_context or {}
        extra_context['rounds_grouped_url'] = reverse('admin:battles_rounds_grouped')
        return super().changelist_view(request, extra_context=extra_context)
    date_hierarchy = 'created_at'

    def get_queryset(self, request):
        """优化查询性能"""
        queryset = super().get_queryset(request)
        return queryset.select_related(
            'player1', 'player2', 'player1_code', 'player2_code'
        ).prefetch_related(
            'rounds'
        )

    fieldsets = (
        ('对战双方', {
            'fields': ('player1', 'player2', 'player1_code', 'player2_code')
        }),
        ('对战状态', {
            'fields': ('status', 'result', 'error_message')
        }),
        ('精彩战斗', {
            'fields': ('is_exciting', 'excitement_score', 'is_manually_marked', 'excitement_calculated_at'),
            'classes': ('wide',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'started_at', 'finished_at')
        }),
        ('对战配置', {
            'fields': ('map_config', 'game_config')
        }),
        ('统计信息', {
            'fields': ('total_rounds', 'player1_score', 'player2_score')
        }),
        ('对战分析', {
            'fields': ('get_battle_analysis',),
            'classes': ('wide',)
        }),
        ('性能图表', {
            'fields': ('get_performance_chart',),
            'classes': ('wide', 'collapse')
        }),
    )

    def get_duration(self, obj):
        """获取对战持续时间"""
        if obj.started_at and obj.finished_at:
            duration = obj.finished_at - obj.started_at
            return f"{duration.total_seconds():.1f}秒"
        return '-'
    get_duration.short_description = '持续时间'

    def get_winner_display(self, obj):
        """获取获胜者显示"""
        if obj.result == 'player1_win':
            return format_html('<span style="color: green; font-weight: bold;">🏆 {}</span>', obj.player1.username)
        elif obj.result == 'player2_win':
            return format_html('<span style="color: green; font-weight: bold;">🏆 {}</span>', obj.player2.username)
        elif obj.result == 'draw':
            return format_html('<span style="color: orange;">🤝 平局</span>')
        else:
            return format_html('<span style="color: gray;">⏳ 未完成</span>')
    get_winner_display.short_description = '获胜者'

    def get_player1_win_rate(self, obj):
        """获取玩家1胜率显示"""
        win_rate = obj.player1_win_rate
        if win_rate >= 70:
            color = 'green'
        elif win_rate >= 50:
            color = 'orange'
        else:
            color = 'red'
        return format_html('<span style="color: {}; font-weight: bold;">{}%</span>', color, f"{win_rate:.1f}")
    get_player1_win_rate.short_description = '玩家1胜率'

    def get_player2_win_rate(self, obj):
        """获取玩家2胜率显示"""
        win_rate = obj.player2_win_rate
        if win_rate >= 70:
            color = 'green'
        elif win_rate >= 50:
            color = 'orange'
        else:
            color = 'red'
        return format_html('<span style="color: {}; font-weight: bold;">{}%</span>', color, f"{win_rate:.1f}")
    get_player2_win_rate.short_description = '玩家2胜率'

    def get_battle_analysis(self, obj):
        """对战分析"""
        if obj.status != 'finished':
            return '对战未完成，无法分析'

        # 计算基本统计
        rounds_data = obj.rounds.all()
        total_rounds = rounds_data.count()

        # 分析代码语言
        p1_lang = obj.player1_code.language if obj.player1_code else '未知'
        p2_lang = obj.player2_code.language if obj.player2_code else '未知'

        # 计算得分差
        score_diff = abs(obj.player1_score - obj.player2_score) if obj.player1_score and obj.player2_score else 0

        # 计算平均每回合时间
        avg_round_time = (obj.finished_at - obj.started_at).total_seconds() / total_rounds if total_rounds > 0 else 0

        analysis_html = """
        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border: 1px solid #dee2e6;">
            <h4 style="margin-top: 0; color: #495057;">📊 对战分析报告</h4>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                <div>
                    <h5>👥 对战信息</h5>
                    <p><strong>玩家1:</strong> {} ({})</p>
                    <p><strong>玩家2:</strong> {} ({})</p>
                    <p><strong>总回合数:</strong> {}</p>
                    <p><strong>得分差:</strong> {}</p>
                </div>
                <div>
                    <h5>🎯 结果分析</h5>
                    <p><strong>获胜者:</strong> {}</p>
                    <p><strong>持续时间:</strong> {}</p>
                    <p><strong>平均每回合时间:</strong> {}秒</p>
                </div>
            </div>
        </div>
        """

        # 获取获胜者信息（避免SafeString问题）
        if obj.result == 'player1_win':
            winner_text = f'🏆 {obj.player1.username}'
        elif obj.result == 'player2_win':
            winner_text = f'🏆 {obj.player2.username}'
        elif obj.result == 'draw':
            winner_text = '🤝 平局'
        else:
            winner_text = '⏳ 未完成'

        # 获取持续时间（避免SafeString问题）
        if obj.started_at and obj.finished_at:
            duration = obj.finished_at - obj.started_at
            duration_text = f"{duration.total_seconds():.1f}秒"
        else:
            duration_text = '-'

        return format_html(
            analysis_html,
            obj.player1.username, p1_lang,
            obj.player2.username, p2_lang,
            total_rounds, score_diff,
            winner_text,
            duration_text,
            f"{avg_round_time:.2f}"
        )
    get_battle_analysis.short_description = '对战分析'

    def get_performance_chart(self, obj):
        """性能图表"""
        if obj.status != 'finished':
            return '对战未完成，无法生成图表'

        # 计算百分比
        max_score = max(obj.player1_score, obj.player2_score, 1)
        p1_width = min(obj.player1_score / max_score * 100, 100)
        p2_width = min(obj.player2_score / max_score * 100, 100)

        # 简单的文本图表显示
        chart_html = """
        <div style="background: #ffffff; padding: 20px; border-radius: 8px; border: 1px solid #dee2e6;">
            <h4 style="margin-top: 0; color: #495057;">📈 性能对比图表</h4>
            <div style="margin: 20px 0;">
                <div style="margin-bottom: 15px;">
                    <label style="display: inline-block; width: 100px; font-weight: bold;">{}:</label>
                    <div style="display: inline-block; width: 200px; height: 20px; background: #e9ecef; border-radius: 10px; overflow: hidden;">
                        <div style="width: {:.1f}%; height: 100%; background: linear-gradient(90deg, #28a745, #20c997); border-radius: 10px;"></div>
                    </div>
                    <span style="margin-left: 10px; font-weight: bold;">{}</span>
                </div>
                <div>
                    <label style="display: inline-block; width: 100px; font-weight: bold;">{}:</label>
                    <div style="display: inline-block; width: 200px; height: 20px; background: #e9ecef; border-radius: 10px; overflow: hidden;">
                        <div style="width: {:.1f}%; height: 100%; background: linear-gradient(90deg, #dc3545, #fd7e14); border-radius: 10px;"></div>
                    </div>
                    <span style="margin-left: 10px; font-weight: bold;">{}</span>
                </div>
            </div>
        </div>
        """

        return format_html(
            chart_html,
            obj.player1.username, p1_width, obj.player1_score,
            obj.player2.username, p2_width, obj.player2_score
        )
    get_performance_chart.short_description = '性能图表'

    def get_exciting_display(self, obj):
        """获取精彩战斗显示"""
        if obj.is_exciting:
            if obj.is_manually_marked:
                return format_html('<span style="color: #ff6b35; font-weight: bold;">🌟 手动标记</span>')
            else:
                return format_html('<span style="color: #28a745; font-weight: bold;">⭐ 自动标记</span>')
        return format_html('<span style="color: #6c757d;">普通</span>')
    get_exciting_display.short_description = '精彩程度'

    def mark_as_exciting(self, request, queryset):
        """手动标记为精彩战斗"""
        # 获取精彩战斗配置
        config = getattr(settings, 'EXCITING_BATTLE', {})
        recalculate_on_manual = config.get('AUTOMATION', {}).get('RECALCULATE_ON_MANUAL_MARK', False)

        count = 0
        for battle in queryset:
            if recalculate_on_manual:
                # 如果配置要求手动标记时重新计算评分
                battle.excitement_score = battle.calculate_excitement_score()
            battle.mark_as_exciting(is_exciting=True, manual=True)
            count += 1
        self.message_user(request, f'成功标记 {count} 场战斗为精彩战斗')
    mark_as_exciting.short_description = '标记为精彩战斗'

    def unmark_as_exciting(self, request, queryset):
        """取消精彩战斗标记"""
        count = 0
        for battle in queryset:
            battle.mark_as_exciting(is_exciting=False, manual=True)
            count += 1
        self.message_user(request, f'成功取消 {count} 场战斗的精彩标记')
    unmark_as_exciting.short_description = '取消精彩战斗标记'

    def calculate_excitement_scores(self, request, queryset):
        """重新计算精彩程度评分"""
        count = 0
        for battle in queryset.filter(status='finished'):
            battle.update_excitement_status(manual_mark=False)
            count += 1
        self.message_user(request, f'成功重新计算 {count} 场战斗的精彩程度评分')
    calculate_excitement_scores.short_description = '重新计算精彩程度评分'

    def get_urls(self):
        """添加自定义URL"""
        urls = super().get_urls()
        custom_urls = [
            path('dashboard/', self.admin_site.admin_view(DashboardView.as_view()), name='battles_dashboard'),
            path('user-dashboard/<int:user_id>/', self.admin_site.admin_view(user_detail_dashboard), name='battles_user_dashboard'),
            path('load-more-rounds/', self.admin_site.admin_view(self.load_more_rounds_view), name='battles_battle_load_more_rounds'),
            path('check-more-rounds/', self.admin_site.admin_view(self.check_more_rounds_view), name='battles_battle_check_more_rounds'),
            path('rounds-grouped/', self.admin_site.admin_view(self.rounds_grouped_view), name='battles_rounds_grouped'),
        ]
        return custom_urls + urls

    def load_more_rounds_view(self, request):
        """Ajax视图：加载更多回合数据"""
        battle_id = request.GET.get('battle_id')
        offset = int(request.GET.get('offset', 0))
        limit = int(request.GET.get('limit', 10))

        try:
            battle = Battle.objects.get(id=battle_id)
            rounds = BattleRound.objects.filter(battle=battle).order_by('round_number')[offset:offset+limit]

            rounds_data = []
            for round_obj in rounds:
                rounds_data.append({
                    'id': round_obj.id,
                    'round_number': round_obj.round_number,
                    'player1_actions': round_obj.player1_actions or '',
                    'player2_actions': round_obj.player2_actions or '',
                    'timestamp': round_obj.timestamp.isoformat() if round_obj.timestamp else ''
                })

            # 检查是否还有更多数据
            total_rounds = BattleRound.objects.filter(battle=battle).count()
            has_more = (offset + limit) < total_rounds

            return JsonResponse({
                'success': True,
                'rounds': rounds_data,
                'has_more': has_more,
                'total_count': total_rounds
            })

        except Battle.DoesNotExist:
            return JsonResponse({
                'success': False,
                'error': '对战不存在'
            })
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            })

    def check_more_rounds_view(self, request):
        """Ajax视图：检查是否有更多回合数据"""
        battle_id = request.GET.get('battle_id')
        current_count = int(request.GET.get('current_count', 0))

        try:
            battle = Battle.objects.get(id=battle_id)
            total_rounds = BattleRound.objects.filter(battle=battle).count()
            has_more = current_count < total_rounds

            return JsonResponse({
                'has_more': has_more,
                'total_count': total_rounds
            })

        except Battle.DoesNotExist:
            return JsonResponse({
                'has_more': False,
                'error': '对战不存在'
            })
        except Exception as e:
            return JsonResponse({
                'has_more': False,
                'error': str(e)
            })

    def export_battle_data(self, request, queryset):
        """导出对战数据"""
        count = queryset.count()
        self.message_user(request, f'已选择 {count} 场对战进行数据导出（功能开发中）')
    export_battle_data.short_description = '导出选中对战数据'

    def analyze_selected_battles(self, request, queryset):
        """分析选中的对战"""
        total = queryset.count()
        finished = queryset.filter(status='finished').count()
        avg_rounds = queryset.filter(status='finished').aggregate(avg=Avg('total_rounds'))['avg'] or 0

        self.message_user(
            request,
            f'分析完成：共 {total} 场对战，其中 {finished} 场已完成，平均回合数 {avg_rounds:.1f}'
        )
    analyze_selected_battles.short_description = '分析选中对战'

    def rounds_grouped_view(self, request):
        """按对战记录分组显示回合数据"""
        from django.template.response import TemplateResponse

        # 获取有回合数据的对战记录
        battles_with_rounds = Battle.objects.filter(
            rounds__isnull=False
        ).distinct().order_by('-created_at')

        # 分页处理
        from django.core.paginator import Paginator
        paginator = Paginator(battles_with_rounds, 10)  # 每页显示10个对战
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)

        # 为每个对战获取回合数据
        battles_data = []
        for battle in page_obj:
            rounds = BattleRound.objects.filter(battle=battle).order_by('round_number')
            battles_data.append({
                'battle': battle,
                'rounds': rounds,
                'total_rounds': rounds.count(),
                'total_actions_p1': sum(len(r.player1_actions) if isinstance(r.player1_actions, (list, tuple)) else (r.player1_actions if r.player1_actions else 0) for r in rounds),
                'total_actions_p2': sum(len(r.player2_actions) if isinstance(r.player2_actions, (list, tuple)) else (r.player2_actions if r.player2_actions else 0) for r in rounds),
            })

        context = {
            'title': '对战回合数据分组视图',
            'battles_data': battles_data,
            'page_obj': page_obj,
            'opts': self.model._meta,
            'has_view_permission': True,
        }

        return TemplateResponse(request, 'admin/battles/rounds_grouped.html', context)



@admin.register(BattleRound)
class BattleRoundAdmin(admin.ModelAdmin):
    list_display = ('get_battle_info', 'get_round_summary', 'get_actions_summary', 'timestamp')
    list_filter = ('battle__status', 'timestamp', 'battle__player1', 'battle__player2')
    search_fields = ('battle__player1__username', 'battle__player2__username')
    readonly_fields = ('timestamp', 'get_battle_rounds_display')
    ordering = ('-battle__created_at', 'round_number')

    def changelist_view(self, request, extra_context=None):
        """自定义列表视图，按对战记录分组显示"""
        from django.template.response import TemplateResponse
        from django.core.paginator import Paginator

        # 获取有回合数据的对战记录，按创建时间倒序
        battles_with_rounds = Battle.objects.filter(
            rounds__isnull=False
        ).distinct().order_by('-created_at')

        # 应用搜索过滤
        search_query = request.GET.get('q', '')
        if search_query:
            battles_with_rounds = battles_with_rounds.filter(
                Q(player1__username__icontains=search_query) |
                Q(player2__username__icontains=search_query)
            )

        # 应用状态过滤
        status_filter = request.GET.get('battle__status__exact')
        if status_filter:
            battles_with_rounds = battles_with_rounds.filter(status=status_filter)

        # 分页处理
        paginator = Paginator(battles_with_rounds, 10)  # 每页显示10个对战
        page_number = request.GET.get('p', 1)
        page_obj = paginator.get_page(page_number)

        # 为每个对战获取回合数据
        battles_data = []
        for battle in page_obj:
            rounds = BattleRound.objects.filter(battle=battle).order_by('round_number')
            battles_data.append({
                'battle': battle,
                'rounds': rounds,
                'total_rounds': rounds.count(),
                'total_actions_p1': sum(len(r.player1_actions) if isinstance(r.player1_actions, (list, tuple)) else (r.player1_actions if r.player1_actions else 0) for r in rounds),
                'total_actions_p2': sum(len(r.player2_actions) if isinstance(r.player2_actions, (list, tuple)) else (r.player2_actions if r.player2_actions else 0) for r in rounds),
            })

        context = {
            'title': '对战回合管理 - 按对战分组',
            'battles_data': battles_data,
            'page_obj': page_obj,
            'opts': self.model._meta,
            'has_view_permission': True,
            'has_add_permission': self.has_add_permission(request),
            'has_change_permission': self.has_change_permission(request),
            'has_delete_permission': self.has_delete_permission(request),
            'search_query': search_query,
            'status_filter': status_filter,
            'cl': self,  # 为了兼容Django admin模板
        }

        if extra_context:
            context.update(extra_context)

        return TemplateResponse(request, 'admin/battles/battleround/change_list_grouped.html', context)

    fieldsets = (
        ('对战信息', {
            'fields': ('battle', 'round_number')
        }),
        ('回合数据', {
            'fields': ('round_data', 'player1_units', 'player2_units')
        }),
        ('玩家行动', {
            'fields': ('player1_actions', 'player2_actions')
        }),
        ('时间信息', {
            'fields': ('timestamp',)
        }),
        ('对战回合总览', {
            'fields': ('get_battle_rounds_display',),
            'classes': ('wide',)
        }),
    )

    def get_battle_info(self, obj):
        """获取对战信息"""
        battle = obj.battle
        status_colors = {
            'waiting': '#6c757d',
            'running': '#007bff',
            'finished': '#28a745',
            'error': '#dc3545'
        }
        status_color = status_colors.get(battle.status, '#6c757d')

        return format_html(
            '<div style="margin-bottom: 5px;">'
            '<strong>🎮 {}</strong><br>'
            '<small style="color: #6c757d;">👤 {} vs {}</small><br>'
            '<span style="color: {}; font-weight: bold;">📊 {}</span>'
            '</div>',
            battle,
            battle.player1.username,
            battle.player2.username,
            status_color,
            battle.get_status_display()
        )
    get_battle_info.short_description = '对战信息'

    def get_round_summary(self, obj):
        """获取回合摘要"""
        total_rounds = BattleRound.objects.filter(battle=obj.battle).count()

        return format_html(
            '<div style="text-align: center;">'
            '<strong style="font-size: 16px; color: #007bff;">第 {} 回合</strong><br>'
            '<small style="color: #6c757d;">共 {} 回合</small>'
            '</div>',
            obj.round_number,
            total_rounds
        )
    get_round_summary.short_description = '回合信息'

    def get_actions_summary(self, obj):
        """获取行动摘要"""
        p1_actions = len(obj.player1_actions) if isinstance(obj.player1_actions, (list, tuple)) else (obj.player1_actions if obj.player1_actions else 0)
        p2_actions = len(obj.player2_actions) if isinstance(obj.player2_actions, (list, tuple)) else (obj.player2_actions if obj.player2_actions else 0)

        return format_html(
            '<div>'
            '<div style="margin-bottom: 5px;">'
            '<span style="color: #28a745; font-weight: bold;">👤 {}:</span> {} 个行动'
            '</div>'
            '<div>'
            '<span style="color: #dc3545; font-weight: bold;">👤 {}:</span> {} 个行动'
            '</div>'
            '</div>',
            obj.battle.player1.username, p1_actions,
            obj.battle.player2.username, p2_actions
        )
    get_actions_summary.short_description = '行动统计'

    def get_battle_rounds_display(self, obj):
        """显示整个对战的回合数据"""
        battle = obj.battle
        rounds = BattleRound.objects.filter(battle=battle).order_by('round_number')

        if not rounds:
            return '暂无回合数据'

        # 构建回合展示HTML
        rounds_html = f"""
        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; border: 1px solid #dee2e6;">
            <h4 style="margin-top: 0; color: #495057;">🎮 对战回合详情 - {battle}</h4>
            <div style="margin-bottom: 15px; padding: 10px; background: #ffffff; border-radius: 5px; border: 1px solid #dee2e6;">
                <strong>对战双方:</strong> {battle.player1.username} vs {battle.player2.username}<br>
                <strong>对战状态:</strong> {battle.get_status_display()}<br>
                <strong>总回合数:</strong> {len(rounds)} 回合<br>
                <strong>创建时间:</strong> {battle.created_at.strftime('%Y-%m-%d %H:%M:%S') if battle.created_at else '未知'}
            </div>
            <div style="max-height: 400px; overflow-y: auto; border: 1px solid #dee2e6; border-radius: 5px;">
                <table style="width: 100%; border-collapse: collapse;">
                    <thead style="background: #e9ecef; position: sticky; top: 0;">
                        <tr>
                            <th style="padding: 8px; border: 1px solid #dee2e6; text-align: center;">回合</th>
                            <th style="padding: 8px; border: 1px solid #dee2e6; text-align: center;">{battle.player1.username} 行动</th>
                            <th style="padding: 8px; border: 1px solid #dee2e6; text-align: center;">{battle.player2.username} 行动</th>
                            <th style="padding: 8px; border: 1px solid #dee2e6; text-align: center;">时间</th>
                        </tr>
                    </thead>
                    <tbody>
        """

        for round_obj in rounds:
            # 当前回合高亮
            row_style = 'background: #fff3cd;' if round_obj.id == obj.id else 'background: #ffffff;'

            p1_actions_count = len(round_obj.player1_actions) if isinstance(round_obj.player1_actions, (list, tuple)) else (round_obj.player1_actions if round_obj.player1_actions else 0)
            p2_actions_count = len(round_obj.player2_actions) if isinstance(round_obj.player2_actions, (list, tuple)) else (round_obj.player2_actions if round_obj.player2_actions else 0)

            rounds_html += f"""
                        <tr style="{row_style}">
                            <td style="padding: 8px; border: 1px solid #dee2e6; text-align: center; font-weight: bold;">
                                {'🔸 ' if round_obj.id == obj.id else ''}第 {round_obj.round_number} 回合
                            </td>
                            <td style="padding: 8px; border: 1px solid #dee2e6; text-align: center;">
                                <span style="color: #28a745; font-weight: bold;">{p1_actions_count} 个行动</span>
                            </td>
                            <td style="padding: 8px; border: 1px solid #dee2e6; text-align: center;">
                                <span style="color: #dc3545; font-weight: bold;">{p2_actions_count} 个行动</span>
                            </td>
                            <td style="padding: 8px; border: 1px solid #dee2e6; text-align: center; font-size: 12px;">
                                {round_obj.timestamp.strftime('%H:%M:%S') if round_obj.timestamp else '未知'}
                            </td>
                        </tr>
            """

        rounds_html += """
                    </tbody>
                </table>
            </div>
            <div style="margin-top: 15px; padding: 10px; background: #d1ecf1; border-radius: 5px; border: 1px solid #bee5eb;">
                <small style="color: #0c5460;">
                    💡 提示：当前查看的是第 {} 回合的详细信息，上表显示了整个对战的所有回合数据。
                </small>
            </div>
        </div>
        """.format(obj.round_number)

        return format_html(rounds_html)
    get_battle_rounds_display.short_description = '对战回合总览'

@admin.register(BattleStatistics)
class BattleStatisticsAdmin(admin.ModelAdmin):
    list_display = ('user', 'total_battles', 'wins', 'losses', 'draws', 'get_win_rate', 'rating', 'current_rank', 'get_activity_status')
    list_filter = ('current_rank', 'updated_at', 'last_battle_at')
    search_fields = ('user__username', 'user__email')
    readonly_fields = ('updated_at', 'last_battle_at', 'get_statistics_chart', 'get_performance_analysis', 'get_recent_battles')
    actions = ['recalculate_statistics', 'reset_rankings']
    ordering = ('-rating', '-total_battles')

    fieldsets = (
        ('用户信息', {
            'fields': ('user',)
        }),
        ('基础统计', {
            'fields': ('total_battles', 'wins', 'losses', 'draws')
        }),
        ('高级统计', {
            'fields': ('total_score', 'average_score', 'best_score')
        }),
        ('排名信息', {
            'fields': ('current_rank', 'highest_rank', 'rating')
        }),
        ('时间信息', {
            'fields': ('last_battle_at', 'updated_at')
        }),
        ('统计图表', {
            'fields': ('get_statistics_chart',),
            'classes': ('wide',)
        }),
        ('性能分析', {
            'fields': ('get_performance_analysis',),
            'classes': ('wide', 'collapse')
        }),
        ('最近对战', {
            'fields': ('get_recent_battles',),
            'classes': ('wide', 'collapse')
        }),
    )

    def get_win_rate(self, obj):
        """计算胜率"""
        if obj.total_battles > 0:
            win_rate = (obj.wins / obj.total_battles) * 100
            color = 'green' if win_rate >= 60 else 'orange' if win_rate >= 40 else 'red'
            win_rate_text = f'{win_rate:.1f}%'
            return format_html(
                '<span style="color: {}; font-weight: bold;">{}</span>',
                color, win_rate_text
            )
        return '0%'
    get_win_rate.short_description = '胜率'

    def get_activity_status(self, obj):
        """获取活跃状态"""
        if not obj.last_battle_at:
            return format_html('<span style="color: gray;">🔘 从未对战</span>')

        days_since_last = (datetime.now().date() - obj.last_battle_at.date()).days
        if days_since_last <= 1:
            return format_html('<span style="color: green;">🟢 今日活跃</span>')
        elif days_since_last <= 7:
            return format_html('<span style="color: orange;">🟡 本周活跃</span>')
        elif days_since_last <= 30:
            return format_html('<span style="color: blue;">🔵 本月活跃</span>')
        else:
            return format_html('<span style="color: red;">🔴 长期未活跃</span>')
    get_activity_status.short_description = '活跃状态'

    def get_statistics_chart(self, obj):
        """统计图表"""
        total = obj.total_battles
        if total == 0:
            return '暂无对战数据'

        win_pct = (obj.wins / total) * 100
        loss_pct = (obj.losses / total) * 100
        draw_pct = (obj.draws / total) * 100

        chart_html = """
        <div style="background: #ffffff; padding: 20px; border-radius: 8px; border: 1px solid #dee2e6;">
            <h4 style="margin-top: 0; color: #495057;">📊 对战统计图表</h4>
            <div style="margin: 20px 0;">
                <div style="margin-bottom: 10px;">
                    <label style="display: inline-block; width: 60px; font-weight: bold; color: #28a745;">胜利:</label>
                    <div style="display: inline-block; width: 200px; height: 20px; background: #e9ecef; border-radius: 10px; overflow: hidden;">
                        <div style="width: {:.1f}%; height: 100%; background: #28a745; border-radius: 10px;"></div>
                    </div>
                    <span style="margin-left: 10px; font-weight: bold;">{} ({:.1f}%)</span>
                </div>
                <div style="margin-bottom: 10px;">
                    <label style="display: inline-block; width: 60px; font-weight: bold; color: #dc3545;">失败:</label>
                    <div style="display: inline-block; width: 200px; height: 20px; background: #e9ecef; border-radius: 10px; overflow: hidden;">
                        <div style="width: {:.1f}%; height: 100%; background: #dc3545; border-radius: 10px;"></div>
                    </div>
                    <span style="margin-left: 10px; font-weight: bold;">{} ({:.1f}%)</span>
                </div>
                <div>
                    <label style="display: inline-block; width: 60px; font-weight: bold; color: #ffc107;">平局:</label>
                    <div style="display: inline-block; width: 200px; height: 20px; background: #e9ecef; border-radius: 10px; overflow: hidden;">
                        <div style="width: {:.1f}%; height: 100%; background: #ffc107; border-radius: 10px;"></div>
                    </div>
                    <span style="margin-left: 10px; font-weight: bold;">{} ({:.1f}%)</span>
                </div>
            </div>
        </div>
        """

        return format_html(chart_html, win_pct, obj.wins, win_pct, loss_pct, obj.losses, loss_pct, draw_pct, obj.draws, draw_pct)
    get_statistics_chart.short_description = '统计图表'

    def get_performance_analysis(self, obj):
        """性能分析"""
        if obj.total_battles == 0:
            return '暂无对战数据进行分析'

        # 计算各种指标
        win_rate = (obj.wins / obj.total_battles) * 100
        avg_score = obj.average_score or 0
        best_score = obj.best_score or 0

        # 评估等级
        if win_rate >= 80:
            level = '🏆 大师级'
            level_color = '#ffd700'
        elif win_rate >= 60:
            level = '💎 专家级'
            level_color = '#20c997'
        elif win_rate >= 40:
            level = '🥉 熟练级'
            level_color = '#fd7e14'
        else:
            level = '🔰 新手级'
            level_color = '#6c757d'

        analysis_html = """
        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border: 1px solid #dee2e6;">
            <h4 style="margin-top: 0; color: #495057;">🎯 性能分析报告</h4>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                <div>
                    <h5>📈 基础指标</h5>
                    <p><strong>总对战:</strong> {} 场</p>
                    <p><strong>胜率:</strong> {:.1f}%</p>
                    <p><strong>平均得分:</strong> {:.1f}</p>
                    <p><strong>最高得分:</strong> {}</p>
                </div>
                <div>
                    <h5>🏅 等级评估</h5>
                    <p><strong>当前等级:</strong> <span style="color: {}; font-weight: bold;">{}</span></p>
                    <p><strong>当前排名:</strong> #{}</p>
                    <p><strong>历史最高:</strong> #{}</p>
                    <p><strong>积分:</strong> {}</p>
                </div>
            </div>
        </div>
        """

        return format_html(
            analysis_html,
            obj.total_battles, win_rate, avg_score, best_score,
            level_color, level,
            obj.current_rank or '未排名',
            obj.highest_rank or '未排名',
            obj.rating
        )
    get_performance_analysis.short_description = '性能分析'

    def get_recent_battles(self, obj):
        """最近对战记录"""
        recent_battles = Battle.objects.filter(
            Q(player1=obj.user) | Q(player2=obj.user)
        ).order_by('-created_at')[:5]

        if not recent_battles:
            return '暂无对战记录'

        battles_html = '<div style="background: #ffffff; padding: 15px; border-radius: 8px; border: 1px solid #dee2e6;">'
        battles_html += '<h4 style="margin-top: 0; color: #495057;">⚔️ 最近5场对战</h4>'

        for battle in recent_battles:
            opponent = battle.player2 if battle.player1 == obj.user else battle.player1
            is_winner = (
                (battle.player1 == obj.user and battle.result == 'player1_win') or
                (battle.player2 == obj.user and battle.result == 'player2_win')
            )

            result_icon = '🏆' if is_winner else '❌' if battle.result != 'draw' else '🤝'
            result_color = 'green' if is_winner else 'red' if battle.result != 'draw' else 'orange'

            battle_item = """
            <div style="padding: 8px; margin: 5px 0; background: #f8f9fa; border-radius: 4px; border-left: 3px solid {};">
                <span style="color: {}; font-weight: bold;">{}</span>
                vs <strong>{}</strong>
                <span style="color: #6c757d; font-size: 0.9em;">({})</span>
            </div>
            """

            battles_html += format_html(
                battle_item,
                result_color, result_color, result_icon,
                opponent.username,
                battle.created_at.strftime('%m-%d %H:%M')
            )

        battles_html += '</div>'
        return mark_safe(battles_html)
    get_recent_battles.short_description = '最近对战'

    def recalculate_statistics(self, request, queryset):
        """重新计算统计数据"""
        count = 0
        for stats in queryset:
            # 这里应该实现重新计算逻辑
            count += 1

        self.message_user(request, f'已重新计算 {count} 个用户的统计数据')
    recalculate_statistics.short_description = '重新计算选中用户统计'

    def reset_rankings(self, request, queryset):
        """重置排名"""
        count = queryset.update(current_rank=None, highest_rank=None)
        self.message_user(request, f'已重置 {count} 个用户的排名信息')
    reset_rankings.short_description = '重置选中用户排名'

    def has_add_permission(self, request):
        # 禁止手动添加统计记录，应该由系统自动创建
        return False
